'use strict'

const router = require('koa-router')();
const fs = require('fs');

function getRouteFiles(filePath) {
    let tmpPath = filePath || __dirname;
    let files = fs.readdirSync(tmpPath);
    let routeFiles = files.filter(item => {
        return item.endsWith('.js') && item !== 'index.js'
    })
    return routeFiles;
}

function registryRoute(router, routeFiles) {
    routeFiles.forEach(item => {
        let tmpPath = __dirname + '/' + item;
        let object = require(tmpPath);
        for (let key in object) {
            let tmArr = key.split(' ');
            let rMethod = tmArr[0];
            let rPath = tmArr[1];
            let rFunction = object[key];
            if (rMethod === 'get') {
                router.get(rPath, rFunction);
            } else if (rMethod === 'post') {
                router.post(rPath, rFunction)
            }else if (rMethod==='put') {
                router.put(rPath, rFunction)
            }else if(rMethod==='delete'){
                router.delete(rPath, rFunction)
            }else{
                console.log('错误请求方法或路径');
            }
        }

    });
    return router.routes();
}

module.exports=function () {
    let routeFiles =getRouteFiles();
    let fn =registryRoute(router,routeFiles);
    return fn;
}